#include <stdio.h>
#include <pcap.h>

#define SNAP_LEN 1518 // 最大捕获数据包长度
#define PORT_SMTP 25 // SMTP 端口号

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
    // 解析数据包中的 TCP 头信息
    const struct sniff_tcp *tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
    u_int size_tcp = TH_OFF(tcp)*4;
    if (size_tcp < 20) {
        printf("Invalid TCP header length: %u bytes\n", size_tcp);
        return;
    }
    
    // 判断是否为 SMTP 流量
    if (ntohs(tcp->th_sport) == PORT_SMTP || ntohs(tcp->th_dport) == PORT_SMTP) {
        printf("Got an SMTP packet!\n");
        
        // 在这里处理 SMTP 数据包
        // ...
    }
}

int main(int argc, char *argv[]) {
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;
    struct bpf_program fp;
    char filter_exp[] = "tcp port 25"; // 过滤规则：捕获 SMTP 流量
    bpf_u_int32 mask;
    bpf_u_int32 net;

    // 打开网络接口进行数据包捕获
    if (pcap_lookupnet(interface, &net, &mask, errbuf) == -1) {
        printf("Could not get netmask for device %s: %s\n", interface, errbuf);
        net = 0;
        mask = 0;
    }
    handle = pcap_open_live(interface, SNAP_LEN, 1, 1000, errbuf);
    if (handle == NULL) {
        printf("Could not open device %s: %s\n", interface, errbuf);
        return 2;
    }

    // 编译并应用过滤器
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
        printf("Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
        return 2;
    }
    if (pcap_setfilter(handle, &fp) == -1) {
        printf("Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
        return 2;
    }

    // 开始捕获数据包
    pcap_loop(handle, -1, got_packet, NULL);

    // 关闭网络接口
    pcap_close(handle);
    return 0;
}
